package api

import (
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"mime"
	"path/filepath"
	"strconv"
	"strings"
	"time"
	"zg3/config"
	"zg3/internal/api/response"
	"zg3/internal/models/dao"
)

const endpoint = "117.27.231.112:9000"
const accessKeyID = "BP8Gcyzz4wAGOQsBLhiD"
const secretAccessKey = "2eTlPvECvmmaoXlXfTXzcRlJKVvNgXsAnPtNXylt"
const bucketName = "zg3"

var map1 = make(map[string]bool)

func Minio(c *gin.Context) {

	value, _ := c.Get("userId")
	userId, _ := strconv.Atoi(value.(string))

	// Initialize minio client object.
	minioClient, _ := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})

	file, err := c.FormFile("file")
	if err != nil {
		log.Fatalln(err)
		return
	}
	open, err := file.Open()
	if err != nil {
		log.Fatalln(err)
		return
	}

	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		log.Fatalln(err)
		return
	}
	times := time.Now().In(location).Truncate(time.Second).Format("20060102150405")

	ext := strings.ToLower(filepath.Ext(file.Filename))

	map1[".mp4"] = true
	map1[".mp5"] = true

	if !map1[ext] {
		response.Response(c, 400, "只能上传视频", nil)
		return
	}

	extension := mime.TypeByExtension(ext)

	obj := times + "/" + file.Filename

	minioClient.PutObject(config.Ctx, bucketName, obj, open, file.Size, minio.PutObjectOptions{ContentType: mime.TypeByExtension(extension)})

	URL := "http://" + endpoint + "/" + bucketName + "/" + obj

	video := dao.Video{
		UserId: userId,
		File:   URL,
	}

	config.DB.Create(&video)

	response.Response(c, 200, "文件上传成功", URL)

}
